package com.example.validdemo.validator;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;


/**
 * 时间格式校验实现
 *
 * @author Bx_Hu
 */
@Slf4j
public class DateValidatorImpl implements ConstraintValidator<DateValidator, String> {

    private String dateFormat;

    @Override
    public void initialize(DateValidator constraintAnnotation) {
        // 获取时间格式
        this.dateFormat = constraintAnnotation.dateFormat();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if (StrUtil.isBlank(value)) {
            return false;
        }
        try {
             DateUtil.parse(value, dateFormat);
            return true;
        } catch (Exception e) {
            log.error("时间格式化异常",e);
            return false;
        }
    }
}
